#!/bin/bash

# API诊断脚本 - 解决接口连接问题

echo "===== API连接诊断工具 ====="
echo "正在检查API服务状态..."

# 检查measurement容器是否在运行
if ! docker compose ps measurement | grep -q "Up"; then
    echo "错误: measurement容器未运行，请先启动后端服务。"
    echo "运行: docker compose up -d measurement"
    exit 1
fi

echo "measurement容器正在运行。"

# 检查measurement容器内的API健康状态
echo "检查API健康状态..."
API_HEALTH=$(docker compose exec measurement curl -s http://localhost:9898/health || echo "连接失败")

if [[ "$API_HEALTH" == "连接失败" ]]; then
    echo "错误: API健康检查失败，后端服务可能未正常启动。"
    echo "请检查后端日志: docker compose logs measurement"
else
    echo "API健康检查成功: $API_HEALTH"
fi

# 检查网络连接
echo "检查容器间网络连接..."
NGINX_TO_API=$(docker compose exec nginx curl -s http://measurement:9898/health || echo "连接失败")

if [[ "$NGINX_TO_API" == "连接失败" ]]; then
    echo "错误: nginx容器无法连接到measurement容器。"
    echo "可能是网络配置问题，请检查Docker网络设置。"
else
    echo "网络连接正常: nginx可以访问measurement API"
fi

# 检查nginx配置
echo "检查nginx配置..."
docker compose exec nginx nginx -t

# 检查logs
echo "检查nginx访问日志中的错误..."
docker compose exec nginx grep -E "50[0-9]|40[0-9]" /var/log/nginx/access.log | tail -n 10

echo "检查nginx错误日志..."
docker compose exec nginx tail -n 20 /var/log/nginx/error.log

echo "检查API服务日志..."
docker compose logs --tail=50 measurement

echo ""
echo "===== 解决方案建议 ====="
echo "1. 如果是CORS问题:"
echo "   - 确认前端请求头设置正确"
echo "   - 确认已添加适当的CORS头到nginx配置"
echo ""
echo "2. 如果是连接超时:"
echo "   - 增加nginx代理超时设置 (已在配置中设置为600s)"
echo "   - 检查后端处理是否需要太长时间"
echo ""
echo "3. 如果是请求体过大:"
echo "   - 已将client_max_body_size设置为20M"
echo "   - 确认前端不发送过大的请求"
echo ""
echo "4. 重新应用配置:"
echo "   docker compose restart nginx measurement"
echo ""
echo "5. 如果问题仍然存在，尝试以下操作:"
echo "   - 清理浏览器缓存"
echo "   - 使用开发者工具检查具体API请求错误"
echo "   - 设置更详细的后端日志级别以获取更多信息"
echo ""
echo "完成诊断。如需进一步帮助，请联系技术支持。" 